package cn.lijiancn01.demo.system.codegen;

import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.codegen.entity.Table;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
public class MyJavaFileGenerator implements IFileGenerator {
    final Marker marker = MarkerFactory.getMarker("MyJavaGenerator");
    private String code;

    public MyJavaFileGenerator(String code) {
        this.code = code;
    }

    @Override
    public GenResult generate(Table table, GlobalConfig globalConfig) {
        GenResult genResult = new GenResult(code);

        MyCustomConfig myCustomConfig = (MyCustomConfig) globalConfig.getCustomConfig(code);
        String packagePath = myCustomConfig.getPackagePath().replace(".", "/");
        File javaFile = new File(globalConfig.getSourceDir(), packagePath + "/" +
                buildClassName(table, myCustomConfig) + ".java");
        //设置其他属性
        myCustomConfig.setImportPackage(myCustomConfig.getPackagePath())
                .setClassFullname(buildClassName(table, myCustomConfig))
        ;

        Map<String, Object> params = new HashMap<>(4);
        params.put("table", table);
        Set<String> ignoreColumns = globalConfig.getStrategyConfig().getIgnoreColumns();
        params.put("commonColumns", table.getColumns().stream().filter(t -> CollectionUtils.isEmpty(ignoreColumns) || !ignoreColumns.contains(t.getName())).toList());
        String createFileContent = myCustomConfig.getMyTemplate().processTemplateIntoString(myCustomConfig.getContent(), params);
        //设置返回值
        genResult.setCreateFilePath(javaFile.getPath());
        genResult.setCreateFileContent(createFileContent);
        genResult.setParams(params);
        //生成文件
        if (myCustomConfig.isCreateFile()) {
            //文件已存在 且 不允许覆盖，直接返回
            if (javaFile.exists() && !myCustomConfig.isOverwriteEnable()) {
                return genResult;
            }
            try {
                FileUtils.write(javaFile, createFileContent);
            } catch (IOException e) {
                log.error(marker, "写入文件异常", e);
            }
        }

        System.out.println(String.format("模板编号：%s ---> %s", code, javaFile));
        return genResult;
    }

    private String buildClassName(Table table, MyCustomConfig config) {
        return config.getClassPrefix() + table.getEntityJavaFileName() + config.getClassSuffix();
    }
}
